import {
  forwardRef,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import { Button } from "@mui/material";
import useAppStore from "../store/hooks";
import toast from "react-hot-toast";
import { observer } from "mobx-react";
import useTicker from "@hooks/useTicker";
import HeroKey from "@assets/hero.key";
import Joystick from "@components/joy-stick";
import "./index.scss";
import sleep from "@/utils/sleep";
import { Settings } from "@mui/icons-material";
import SettingsModal, {
  SettingsModalInstance,
} from "@/components/settings-modal";
import Timer from "@/components/timer";
import RippleButton from "@/components/ripple-button/ripple-button";
import useRipple from "@/components/ripple-button/useRipple";

export interface ControllerInstance {
  handlePause?: () => void;
  handleReset?: () => void;
  handleHeroClick?: () => void;
}

const Controller = observer(
  forwardRef((props, ref) => {
    const store = useAppStore("store");
    const settingsRef = useRef<SettingsModalInstance>(null);

    const [sec, setSec] = useState(0);

    const ticker = useTicker(
      (tick) => {
        setSec((pre) => pre + 1);
      },
      {
        immediate: false,
        pauseAtFirst: true,
        duration: 1000,
      }
    );

    function handlePause() {
      ticker.status === "on"
        ? (function () {
            ticker.pause();
            store.joyStick.dragglable = false;
          })()
        : function () {
            if (ticker.tick === 0) {
              Promise.queue([
                () => sleep(0).then(() => toast("3", { icon: "⏰" })),
                () => sleep(1000).then(() => toast("2", { icon: "⏰" })),
                () => sleep(1000).then(() => toast("1", { icon: "⏰" })),
                () =>
                  sleep(1000).then(() => {
                    toast("Go!", { icon: "🚀" });
                    store.joyStick.dragglable = true;
                    return void 0;
                  }),
              ]);
              ticker.delayedResume(3000);
            } else {
              ticker.resume();
              store.joyStick.dragglable = true;
            }
            // @ts-ignore
          }.call(this);
    }

    function handleReset() {
      store.joyStick.dragglable = false;
      store.joyStick.isDragging = false;
      ticker.pause();
      ticker.reset();
      setSec(0);
      store.setSite({ x: 0, y: 0 });
      store.setHero(
        store.hero.name === HeroKey["New Jersey"]
          ? HeroKey["Shinanon"]
          : HeroKey["New Jersey"]
      );
    }

    function handleSetting() {
      settingsRef.current?.open();
    }

    useImperativeHandle(ref, () => ({
      handlePause,
      handleReset,
      handleHeroClick: () => {
        toast(`You got it!`, {
          icon: "👏",
        });
        handleReset();
      },
    }));

    const ripple = useRipple<HTMLDivElement>();

    return (
      <div className="App-controller">
        <Timer sec={sec} />
        <Button
          className="cg-btn"
          variant="contained"
          onClick={handlePause}
          color={ticker.status === "on" ? "warning" : "primary"}
        >
          {ticker.status === "on"
            ? "Pause"
            : ticker.tick === 0
            ? "Start"
            : "Go On"}
        </Button>
        <div className="game-title" ref={ripple}>
          Azure Lane React
        </div>
        <Button
          className="reset-btn"
          variant="contained"
          onClick={handleReset}
          color="secondary"
        >
          Reset
        </Button>
        <Button className="settings-btn" onClick={handleSetting}>
          <Settings color="secondary" />
        </Button>
        <Joystick />
        <SettingsModal ref={settingsRef} />
      </div>
    );
  })
);

export default Controller;
